package com.example.springboot.filter;

import com.example.springboot.entity.SecurityUser;
import com.example.springboot.entity.Users;
import com.example.springboot.security.TokenManager;
import com.example.springboot.util.R;
import com.example.springboot.util.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 认证给过滤器
 * @default
**/
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private TokenManager tokenManager;
    private AuthenticationManager authenticationManager;
    ObjectMapper objectMapper = new ObjectMapper();
    private RedisTemplate<String,String> redisTemplate;

    public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager,RedisTemplate<String,String> redisTemplate) {
        super(authenticationManager);
        this.tokenManager = tokenManager;
        this.authenticationManager = authenticationManager;
        this.redisTemplate = redisTemplate;
        // 必须是 post 请求方式
        this.setPostOnly(true);
        // 设置登录路径，让是POST提交
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login","POST"));
    }

    /**
     * 获取表单提交账号和密码
     * @default
    **/
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            Users users = objectMapper.readValue(request.getInputStream(), Users.class);
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                    new UsernamePasswordAuthenticationToken(
                            users.getName(),
                            users.getPassword(),
                            new ArrayList<>());
            return authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        } catch (IOException e) {
            e.printStackTrace();
            throw new AccountExpiredException(e.getMessage());
        }
    }
    /**
     * 认证成功方法
     * @default
    **/
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        // 认证成功，得到认证成功之后用户信息
        SecurityUser securityUser = (SecurityUser) authResult.getPrincipal();
        // 根据用户名生成Token
        String token = tokenManager.createToken(securityUser.getUsername());
        // 把用户名称和用户权限列表放到redis TODO
        securityUser.getPermissionValueList();
        String json = objectMapper.writeValueAsString(securityUser.getCurrentUserInfo());
        // 用户信息
        redisTemplate.opsForValue().set(token+"authentic",json);
        // 用户权限
        redisTemplate.opsForList().leftPushAll(token+"author",securityUser.getPermissionValueList());
        // 返回token
        ResponseUtil.out(response, R.ok(new HashMap<String,Object>(3){{
            put("token",token);
        }}));
    }
    /**
     * 认证失败方法
     * @default
    **/
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        ResponseUtil.out(response, R.error(failed.getMessage()));
    }
}
